﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using HF.Framework.DataClientDBAgent;
using HF.WorkFlow.DataContract;
using HF.Framework.SqlDataContract;
using HF.WorkFlow.Const;
namespace HF.WorkFlow.Engine
{
    /// <summary>
    /// 数据访问类AccreditUser。
    /// </summary>
    public class AccreditUser
    {
        #region  私有字段
        private SqlDataItem sqlDataItem = new SqlDataItem();
        private string[] fieldList = { "AccreditId", "AccreditFromUserId", "AccreditToUserId", "AccreditDateTime", "AccreditStatus", "WorkFlowId", "WorkTaskId",
                                         "Description","AccreditFromName","AccreditToName","AcceditStartTime","AcceditEndTime","AccreditName",
                                         "AccreditMatters","AcceditCancelTime" };
        private string tableName = "HF_AccreditUser";
        private string keyField = "AccreditId";
        private string sqlString = "";

        #endregion

        #region  私有方法
        private void setParameter(AccreditUserEntity entity)
        {
            sqlDataItem.ParameterList.Clear();
            sqlDataItem.AppendParameter("@AccreditId", entity.AccreditId, typeof(string));
            sqlDataItem.AppendParameter("@AccreditFromUserId", entity.AccreditFromUserId, typeof(string));
            sqlDataItem.AppendParameter("@AccreditToUserId", entity.AccreditToUserId, typeof(string));
            sqlDataItem.AppendParameter("@AccreditDateTime", entity.AccreditDateTime, typeof(DateTime));
            sqlDataItem.AppendParameter("@AccreditStatus", entity.AccreditStatus, typeof(char));
            sqlDataItem.AppendParameter("@WorkFlowId", entity.WorkFlowId, typeof(string));
            sqlDataItem.AppendParameter("@WorkTaskId", entity.WorkTaskId, typeof(string));
            sqlDataItem.AppendParameter("@Description", entity.Description, typeof(string));
            sqlDataItem.AppendParameter("@AccreditFromName", entity.AccreditFromName, typeof(string));
            sqlDataItem.AppendParameter("@AccreditToName", entity.AccreditToName, typeof(string));
            sqlDataItem.AppendParameter("@AcceditStartTime", entity.AcceditStartTime, typeof(DateTime));
            sqlDataItem.AppendParameter("@AcceditEndTime", entity.AcceditEndTime, typeof(DateTime));
            sqlDataItem.AppendParameter("@AccreditName", entity.AccreditName, typeof(string));
            sqlDataItem.AppendParameter("@AccreditMatters", entity.AccreditMatters, typeof(char));
            sqlDataItem.AppendParameter("@AcceditCancelTime", entity.AcceditCancelTime, typeof(DateTime));
         }

        private void setInsertSql()
        {
            string tmpValueList = "";
            string tmpFieldName = "";
            sqlString = "insert into " + tableName + "(";
            int tmpInt = this.fieldList.Length;
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + ", ";
                tmpValueList = tmpValueList + "@" + tmpFieldName + ",";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName;
            tmpValueList = tmpValueList + "@" + tmpFieldName;
            this.sqlString = sqlString + ")values(" + tmpValueList + ")";
            sqlDataItem.CommandText = sqlString;
        }

        private void setUpdateSql()
        {
            string tmpFieldName = "";
            int tmpInt = this.fieldList.Length;
            sqlString = "update " + tableName + " set ";
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName + ", ";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName;
            sqlString = sqlString + " where " + keyField + "=@" + this.keyField;
            sqlDataItem.CommandText = sqlString;
        }

        public AccreditUserEntity GetAccreditUserEntity(DataRow dr)
        {
            AccreditUserEntity entity = new AccreditUserEntity();
            string value = "";
            entity.AccreditId = dr["AccreditId"].ToString();
            entity.AccreditFromUserId = dr["AccreditFromUserId"].ToString();
            entity.AccreditToUserId = dr["AccreditToUserId"].ToString();
            value = dr["AccreditDateTime"].ToString();
            if (string.IsNullOrEmpty(value) == false)
            {
                entity.AccreditDateTime = Convert.ToDateTime(value);
            }
            entity.AccreditStatus = Convert.ToChar(dr["AccreditStatus"].ToString());
            entity.WorkFlowId = dr["WorkFlowId"].ToString();
            entity.WorkTaskId = dr["WorkTaskId"].ToString();
            entity.Description = dr["Description"].ToString();

            entity.AccreditFromName = dr["AccreditFromName"].ToString();
            entity.AccreditToName = dr["AccreditToName"].ToString();
            if (string.IsNullOrEmpty(dr["AcceditStartTime"].ToString()) == false)
            {
                entity.AcceditStartTime = Convert.ToDateTime(dr["AcceditStartTime"].ToString());
            }
            if (string.IsNullOrEmpty(dr["AcceditEndTime"].ToString()) == false)
            {
                entity.AcceditEndTime = Convert.ToDateTime(dr["AcceditEndTime"].ToString());
            }
            entity.AccreditName = dr["AccreditName"].ToString();
            
            entity.AccreditMatters = Convert.ToChar(dr["AccreditMatters"]);

            entity.AcceditCancelTime = Convert.ToDateTime(dr["AcceditCancelTime"].ToString());
            return entity;
        }

        #endregion

        #region  构造函数
        public AccreditUser()
        { }
        public static AccreditUser GetInstance()
        {
            return new AccreditUser();
        }
        #endregion

        #region  公有方法
        #region  基本方法
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Insert(AccreditUserEntity entity)
        {
            try
            {
                setInsertSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Update(AccreditUserEntity entity)
        {
            try
            {
                setUpdateSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string accreditId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = tmpSql;
            sqlItem.AppendParameter("@" + keyField, accreditId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="accreditId">主键Id</param>
        /// <returns>影响的记录条数</returns>
        public void Delete(string accreditId)
        {
            try
            {
                string tmpSql = "delete from " + tableName + " where  " + keyField + "=@" + keyField;
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, accreditId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一条数据记录
        /// </summary>
        /// <param name="AccreditId">主键Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetAccreditUserTable(string accreditId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, accreditId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一个数据实体
        /// </summary>
        /// <param name="accreditId">主键Id</param>
        /// <returns>DataTable</returns>
        public AccreditUserEntity GetAccreditUserEntity(string accreditId)
        {
            DataTable dt = GetAccreditUserTable(accreditId);
            if (dt != null && dt.Rows.Count > 0)
            {
                return GetAccreditUserEntity(dt.Rows[0]);
            }
            return null;
        }

        #endregion

        #region  扩展方法
        //此处添加扩展方法
        public  string AssignAccredit(string fromUserId, string toUserId, string workFlowId, string workTaskId)
        {
            try
            {
                ClientDBAgent agent = new ClientDBAgent();
                AccreditUserEntity entity = new AccreditUserEntity();
                entity.AccreditId = Guid.NewGuid().ToString();
                entity.AccreditFromUserId = fromUserId;
                entity.AccreditToUserId = toUserId;
                entity.WorkFlowId = workFlowId;
                entity.WorkTaskId = workTaskId;
                entity.AccreditStatus = '1';
                entity.AccreditDateTime = Convert.ToDateTime(agent.GetDBDateTime());
                AccreditUser.GetInstance().Insert(entity);
                return WorkFlowConst.SuccessCode;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 收回代理
        /// </summary>
        /// <param name="accreditId"></param>
        /// <param name="satues"></param>
        public bool RemoveMoveAccredit(string accreditId, bool reults, DateTime AcceditCancelTime)
        {
            string sql = string.Empty;
            if (reults)
            {
                sql = "update HF_AccreditUser set accreditstatus='0',AccreditMatters = '2',AcceditCancelTime='" + AcceditCancelTime + "' where AccreditId=@AccreditId";
            }
            else 
            {
                sql = "update HF_AccreditUser set accreditstatus='0' where AccreditId=@AccreditId";
            }
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@AccreditId", accreditId);
            ClientDBAgent agent = new ClientDBAgent();
            DataTable table = agent.ExecuteDataTable(sqlItem);
            if (table.Rows.Count > 0)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 收回代理(所有)
        /// </summary>
        /// <param name="fromUserId"></param>
        /// <param name="toUserId"></param>
        public bool RemoveAccredit(string fromUserId, string toUserId, bool reults, DateTime AcceditCancelTime)
        {
            //accreditstatus='3' 是收回流转中流程
            //accreditstatus='0' 是收回流程
            string sql = string.Empty;
            if (reults)
            {
                sql = "update HF_AccreditUser set accreditstatus='0',AccreditMatters = '2',AcceditCancelTime='" + AcceditCancelTime + "' where AccreditToUserId=@AccreditToUserId and  AccreditFromUserId=@AccreditFromUserId";
            }
            else 
            {
                sql = "update HF_AccreditUser set accreditstatus='0' where AccreditToUserId=@AccreditToUserId and  AccreditFromUserId=@AccreditFromUserId";
            }
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@AccreditToUserId", toUserId);
            sqlItem.AppendParameter("@AccreditFromUserId", fromUserId);
            ClientDBAgent agent = new ClientDBAgent();
            DataTable table = agent.ExecuteDataTable(sqlItem);
            if (table.Rows.Count > 0)
            {
                return true;
            }
            return false;
        }
        public bool Exists(string fromUserId, string toUserId, string workFlowId, string workTaskId)
        {
            string sql = "select * from HF_AccreditUser where AccreditFromUserId=@fromUserId and " +
                         " AccreditToUserId=@toUserId and WorkflowId=@WorkflowId and " +
                          "WorktaskId=@WorktaskId and AccreditStatus='1'";//有效的授权是否存在
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@fromUserId", fromUserId);
            sqlItem.AppendParameter("@toUserId", toUserId);
            sqlItem.AppendParameter("@WorkflowId", workFlowId);
            sqlItem.AppendParameter("@WorktaskId", workTaskId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);

        }
        /// <summary>
        /// 判断用户是否是该任务节点的操作者，如果不是不允许授权该任务.
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="workFlowId">流程模板Id</param>
        /// <param name="workTaskId">任务模板Id</param>
        /// <returns></returns>
        public  bool IsTaskOperator(string userId, string workFlowId, string workTaskId)
        {
            string sql = "select  operContent from HF_operator  where (" +
                        "(OperContent IN (SELECT OperContent FROM HF_opercontentView where UserId=@userId) or OperContent='ALL' ) and " +
                        " workflowId=@workflowId and worktaskId=@worktaskId)";
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@userId", userId);
            sqlItem.AppendParameter("@workflowId", workFlowId);
            sqlItem.AppendParameter("@worktaskId", workTaskId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }
        /// <summary>
        /// 已授出的权限
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns>DataTable</returns>
        public  DataTable GetToAccreditTable(string userId)
        {
            string sql = "select * from HF_WorkTaskAccreditView where accreditStatus='1' and accreditFromUserId=@userId" +
                          " order by flowcaption,taskcaption";
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@userId", userId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.ExecuteDataTable(sqlItem);

        }
        
        /// <summary>
        /// 被授予的权限
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns>DataTable</returns>
        public  DataTable GetHaveAccreditTable(string userId)
        {
            string sql = "select * from HF_WorkTaskAccreditView where accreditStatus='1' and accreditToUserid=@userId" +
                          " order by flowcaption,taskcaption";
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@userId", userId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.ExecuteDataTable(sqlItem);
        }
        /// <summary>
        /// 操作者.
        /// </summary>
        public DataTable TaskOperator()
        {
            string sql = "select  * from HF_operator";
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            ClientDBAgent agent = new ClientDBAgent();
            return agent.ExecuteDataTable(sqlItem);
        }
        /// <summary>
        /// 处理者信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public DataTable GetOpercontent(string userId)
        {
            string sql = "select OperContent FROM HF_opercontentView where UserId=@userId";
                 
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@userId", userId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.ExecuteDataTable(sqlItem);
        }
        #endregion
        #endregion

        #region  方法

        /// <summary>
        /// 流程代理新增
        /// </summary>
        /// <param name="entitys">流程代理实例</param>
        /// <returns></returns>
        public bool AddAccreditUser(List<AccreditUserEntity> entitys)
        {
            try
            {

                ClientDBAgent agent = new ClientDBAgent();
                foreach (AccreditUserEntity item in entitys)
                {
                    int i = AccreditUser.GetInstance().Insert(item);
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 当前操作人代理状况
        /// </summary>
        /// <param name="accreditToUserId">操作人ID</param>
        /// <returns></returns>
        public DataTable GetOwnAccreditUser(string accreditFromUserId)
        {
            try
            {
                string sql = " select  ROW_NUMBER() OVER (ORDER BY AccreditFromUserId DESC) AS Number," +
                     "  AccreditFromName,AccreditFromUserId,AccreditToName,AccreditToUserId,COUNT(AccreditToUserId) as Count " +
                     "  from HF_AccreditUser where AccreditFromUserId = @AccreditFromUserId " +
                     "  group by AccreditToUserId,AccreditFromUserId,AccreditFromName,AccreditToName";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@AccreditFromUserId", accreditFromUserId);
                ClientDBAgent agent = new ClientDBAgent();
                DataTable table = agent.ExecuteDataTable(sqlItem);
                return table;
            }
            catch (Exception)
            {
                return null;
                throw;
            }
         
        }

        /// <summary>
        /// 其它操作人代理状况
        /// </summary>
        /// <param name="accreditToUserId">操作人ID</param>
        /// <returns></returns>
        public DataTable GetOtherAccreditUser(string accreditFromUserId)
        {
            try
            {
                string sql = " select  ROW_NUMBER() OVER (ORDER BY AccreditFromUserId DESC) AS Number," +
                     "  AccreditFromName,AccreditFromUserId,AccreditToName,AccreditToUserId,COUNT(AccreditToUserId) as Count " +
                     "  from HF_AccreditUser where AccreditFromUserId <> @AccreditFromUserId " +
                     "  group by AccreditToUserId,AccreditFromUserId,AccreditFromName,AccreditToName";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@AccreditFromUserId", accreditFromUserId);
                ClientDBAgent agent = new ClientDBAgent();
                DataTable table = agent.ExecuteDataTable(sqlItem);
                return table;
            }
            catch (Exception)
            {
                return null;
                throw;
            }

        }
        /// <summary>
        /// 流程代理查询
        /// </summary>
        /// <param name="url">SQL语句条件</param>
        /// <returns></returns>
        public DataTable GetAccreditList(string  url)
        {
            try
            {
                string sql = " select * from HF_AccreditWorkFlowView where " + url + " order by Caption";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                ClientDBAgent agent = new ClientDBAgent();
                DataTable table = agent.ExecuteDataTable(sqlItem);
                return table;
            }
            catch (Exception)
            {
                return null;
                throw;
            }
        }
        /// <summary>
        /// 流程代理明细
        /// </summary>
        /// <param name="accreditToUserId">操作人ID</param>
        /// <param name="accreditFromUserId">被操作人ID</param>
        /// <returns></returns>
        public DataTable GetAccreditUserList(string accreditToUserId, string accreditFromUserId)
        {
            try
            {
                string sql = " select * from HF_AccreditWorkFlowView where AccreditToUserId =@AccreditToUserId and AccreditFromUserId=@AccreditFromUserId" +
                            " order by Caption";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@AccreditToUserId", accreditToUserId);
                sqlItem.AppendParameter("@AccreditFromUserId", accreditFromUserId);
                ClientDBAgent agent = new ClientDBAgent();
                DataTable table = agent.ExecuteDataTable(sqlItem);
                return table;
            }
            catch (Exception)
            {
                return null;
                throw;
            }
        }

        /// <summary>
        /// 流程类型
        /// </summary>
        /// <param name="accreditToUserId">操作人ID</param>
        /// <param name="accreditFromUserId">被操作人ID</param>
        /// <returns></returns>
        public DataTable GetWorkFlowCaptions(string accreditToUserId, string accreditFromUserId)
        {
            try
            {
                string sql = " select distinct Caption,WFClassId from HF_AccreditWorkFlowView where AccreditToUserId =@AccreditToUserId and AccreditFromUserId=@AccreditFromUserId" +
                            " order by Caption";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@AccreditToUserId", accreditToUserId);
                sqlItem.AppendParameter("@AccreditFromUserId", accreditFromUserId);
                ClientDBAgent agent = new ClientDBAgent();
                DataTable table = agent.ExecuteDataTable(sqlItem);
                return table;
            }
            catch (Exception)
            {
                return null;
                throw;
            }
        }

        /// <summary>
        /// 流程名称
        /// </summary>
        /// <param name="accreditToUserId">操作人ID</param>
        /// <param name="accreditFromUserId">被操作人ID</param>
        /// <returns></returns>
        public DataTable GetInstanceCaption(string accreditToUserId, string accreditFromUserId)
        {
            try
            {
                string sql = " select distinct FlowCaption,WorkFlowId from HF_AccreditWorkFlowView where AccreditToUserId =@AccreditToUserId and AccreditFromUserId=@AccreditFromUserId" +
                            " order by FlowCaption";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@AccreditToUserId", accreditToUserId);
                sqlItem.AppendParameter("@AccreditFromUserId", accreditFromUserId);
                ClientDBAgent agent = new ClientDBAgent();
                DataTable table = agent.ExecuteDataTable(sqlItem);
                return table;
            }
            catch (Exception)
            {
                return null;
                throw;
            }
        }


        /// <summary>
        /// 查询所有流程
        /// </summary>
        /// <returns></returns>
        public DataTable GetWorkFlowList()
        {
            try
            {
                string sql = @" select * from HF_WorkFlow ";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                ClientDBAgent agent = new ClientDBAgent();
                DataTable table = agent.ExecuteDataTable(sqlItem);
                return table;
            }
            catch (Exception)
            {
                return null;
                throw;
            }
        }

        /// <summary>
        /// 查询所有流程列表
        /// </summary>
        /// <returns></returns>
        public DataTable GetWorkFlowClass()
        {
            try
            {
                string sql = @" select * from HF_WorkFlowClass ";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                ClientDBAgent agent = new ClientDBAgent();
                DataTable table = agent.ExecuteDataTable(sqlItem);
                return table;
            }
            catch (Exception)
            {
                return null;
                throw;
            }
        }
        #endregion
    }
}

